package listener

import (
    "encoding/json"
    "fmt"
    
    "collecter/app/common/helper"
    "collecter/app/event/interfaces"
    "collecter/app/model"
)

type UpdateCollect struct {
    EventName   string
    SubjectId   int64
    ExtraParams string
}

func (uc UpdateCollect) SetValue(eventName string, subjectId int64, extraParams string) interfaces.EventInterfacer {
    uc.EventName = eventName
    uc.SubjectId = subjectId
    uc.ExtraParams = extraParams
    return uc
}

func (uc UpdateCollect) Handle() error {
    fmt.Println("CreateCollect event is listen ... ")
    fmt.Printf(" CreateCollect-->Handle: %+v\n", uc)
    
    oldCollect := model.Collects{}
    collect := model.Collects{Id: uc.SubjectId}
    if err := helper.Db.Where(&collect).First(&collect).Error; err != nil {
        errmsg := "更新收藏内容事件监听失败：查询收藏记录失败。errmsg：" + err .Error()
        helper.Logger.WithField("appert", "eventerr").Error(errmsg)
        return nil
    }
    if 1 == collect.ContentType {
        // 收藏的内容不是文件
        return nil
    }
    if err := json.Unmarshal([]byte(uc.ExtraParams), &oldCollect); err != nil {
        errmsg := "更新收藏内容事件监听失败：反序列化额外参数失败。errmsg：" + err .Error()
        helper.Logger.WithField("appert", "eventerr").Error(errmsg)
        return nil
    }
    if collect.Content == oldCollect.Content {
        // 文件未做修改，不做处理
        return nil
    }
    collect.SourceUrl = collect.Content
    if 2 == collect.ContentType {
        collect.Ext = helper.GetExt(collect.Content)
        if err := handleCollectFile(&collect, "修改"); err != nil {
            return nil
        }
    } else if 3 == collect.ContentType {
        collect.Remark = "收藏内容是一个 url "
    }
    
    if err := helper.Db.Save(&collect).Error; err != nil {
        errmsg := "修改收藏内容事件监听失败：更新收藏记录失败。errmsg：" + err .Error()
        helper.Logger.WithField("appert", "eventerr").Error(errmsg)
        return nil
    }
    _ = helper.Unlink(oldCollect.Content)
    return nil
}